/**
 * Created by Administrator on 2017/4/6.
 */
/**
 * Created by neal on 11/22/16.
 */

var Config = {
    createUrl: '/api/goods',
    updateUrl: '/api/goods',
    updateUrlForCellEdit: '/api/goods/cellEdit',
    deleteUrl: '/api/goods',
    selectUrl: '/api/goods'
};
$().ready(function () {
    $("#datepicker").datepicker({keyboardNavigation: !1, forceParse: !1, autoclose: !0});
    $.ajax(
        {
            url:'/api/companyInfo',
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data) {
                if(data && data.data){
                    $("#goodsProviderId").val(data.data.companyId);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.error(errorThrown);
            }
        }
    );
    $.ajax(
        {
            url: '/api/admin/categories/get',
            type: "GET",
            dataType: "json",
            async: false,
            success: function (data, textStatus, jqXHR) {
                var categories = [];
                categories.push('<option value="" hassubinfo="true">全部分类</option>');
                data.data.map(function (category) {
                    categories.push('<option value="');
                    categories.push(category.categoryId);
                    categories.push('" ');
                    categories.push('hassubinfo="true">');
                    categories.push(category.categoryName);
                    categories.push('</option>');
                });
                $("#categoryId").html(categories.join(''));
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    $.jgrid.defaults.styleUI = "Bootstrap";
    console.log($("input[name=goodsProviderId]").val())
    $("#data_list").jqGrid({
        datatype: "json",
        url: '/api/ws/goods',
        height: 450,
        autowidth: true,
        shrinkToFit: true,
        rowNum: 12,
        colNames: ["编号", "商品名称", "折扣", "出售价(元)", "进货价(元)", "红包", "上架&下架", "精品", "新品", "购买方式", "推荐排序", "操作"],
        colModel: [{
            name: "goodsId",
            index: "goodsId",
            autowidth: true,
            sorttype: "int",
            search: true
        }, {
            name: "goodsName",
            index: "goodsName",
            autowidth: true
        }, {
            name: "discount",
            index: "discount",
            autowidth: true,
            sorttype: "int"
        }, {
            name: "goodsScreenPrice",
            index: "goodsScreenPrice",
            sorttype: "int",
            autowidth: true
        }, {
            name: "goodsRealPrice",
            index: "goodsRealPrice",
            sorttype: "int",
            autowidth: true
        }, {
            name: "goodsScore",
            index: "goodsScore",
            sorttype: "int",
            autowidth: true
        },{
            name: "goodsOnline",
            index: "goodsOnline",
            autowidth: true,
            editable: true,
            sortable: true,
            editoptions:{value:"0:下架;1:上架"},
            edittype:'select',
            formatter:'select'
        }, {
            name: "best",
            index: "best",
            sortable: false,
        }, {
            name: "newest",
            index: "newest",
            sortable: false
        }, {
            name: "goodsPayType",
            index: "goodsPayType",
            sortable: false,
        }, {
            name: "goodsRecommendSort",
            index: "goodsRecommendSort",
            autowidth: true,
            editable: true,
            sortable: true
        }, {
            name: "operate",
            index: "operate",
            autowidth: true,
            sortable: false
        }],
        cellEdit: true,
        cellsubmit: 'remote',
        cellurl: Config.updateUrlForCellEdit,
        pager: "#pager_data_list",
        jsonReader: {
            root: "data", "page": "page", total: "total",
            records: "records", repeatitems: false, id: "goodsId"
        },
        viewrecords: true,
        hidegrid: false,
        gridComplete: function () {
            //wrapper operate
            dataWrapper();
        }
    });
    $("#perform_search").click(function() {
        var postdata = $("#data_list").jqGrid('getGridParam','postData');
        postdata._search = true;
        postdata.categoryId = $('#categoryId option:selected') .val();
        postdata.goodsBrand = $('#goodsBrand option:selected') .val();
        postdata.goodsOnline = $('#goodsOnline option:selected') .val();
        postdata.onlineGoods = $('#onlineGoods option:selected') .val();
        postdata.goodsName = $('#textGoodsName').val();
        jQuery("#data_list").trigger("reloadGrid",[{page:1}]);
    });
    jQuery("#data_list").jqGrid('navGrid', '#pager_data_list', {
        add: false,
        edit: false,
        del: false,
        search: false,
        refresh: false
    });
    $(window).bind("resize", function () {
        var width = $(".jqGrid_wrapper").width();
        $("#data_list").setGridWidth(width);
    });
});

function Delete(id) {
    updateDialog("DELETE", Config.deleteUrl + '/' + id, id);
}

function updateDialog(action, url, id) {
    $.ajax(
        {
            url: url,
            type: action,
            dataType: "json",
            success: function (data, textStatus, jqXHR){
                if (action == 'DELETE') {
                    if (data && data.type == "SUCCESS"){
                        jQuery("#data_list").jqGrid('delRowData', id);
                        jQuery("#data_list").trigger("reloadGrid");
                    }else{
                        toastr.error(data.msg);
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error("该角色下有关联的权限，请先删除.");
            }
        });
}
function dataWrapper() {
    var ids = jQuery("#data_list").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var id = ids[i];
        var dataFromTheRow = jQuery('#data_list').jqGrid ('getRowData', id);
        var html = '<a class="J_menuItem" style="color:#f60;padding-right: 15px" href="/ws/goods/update/' + id + '" data-index="0">编辑</a>';
        html += "<a style='color:#f60' onclick='Delete(" + id + ")' >删除</a>";
        var goodsPayTypeText = "无";
        switch(Number(dataFromTheRow.goodsPayType)){
            case 0:
                goodsPayTypeText = "现金";
                break;
            case 1:
                goodsPayTypeText = "红包";
                break;
            case 2:
                goodsPayTypeText = "现金+红包";
                break;
        }
        var discount = (dataFromTheRow.goodsRealPrice/dataFromTheRow.goodsScreenPrice).toFixed(2)*100;
        if(isNaN(discount)){
            discount = 0;
        }else{
            discount = discount;
        }
        jQuery("#data_list").jqGrid('setRowData', ids[i], {
            operate: html,
            goodsPayType: goodsPayTypeText,
            goodsScreenPrice: toFixedForPrice(dataFromTheRow.goodsScreenPrice),
            goodsRealPrice: toFixedForPrice(dataFromTheRow.goodsRealPrice),
            discount: discount
        });
    }
}
